package com.ky.tms.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ky.tms.entity.*;
import com.ky.tms.enums.CostEnum;
import com.ky.tms.enums.OrderEnum;
import com.ky.tms.enums.TransCode;
import com.ky.tms.exception.PredictableException;
import com.ky.tms.mapper.TmsCostMapper;
import com.ky.tms.mapper.TmsCostOrderMapper;
import com.ky.tms.mapper.TmsOrderMapper;
import com.ky.tms.mapper.TmsPayLogMapper;
import com.ky.tms.service.ITmsCostService;
import com.ky.tms.util.*;
import com.ky.tms.vo.CostFinish;
import com.ky.tms.vo.CostOrders;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengkaimao
 * @since 5050-05-54
 */
@Service
public class TmsCostServiceImpl extends ServiceImpl<TmsCostMapper, TmsCost> implements ITmsCostService {

    @Autowired
    private TmsCostMapper tmsCostMapper;

    @Autowired
    private TmsOrderMapper tmsOrderMapper;

    @Autowired
    private TmsCostOrderMapper tmsCostOrderMapper;

    @Autowired
    private TmsPayLogMapper tmsPayLogMapper;

    //商户号
    private static String merNo = "10001004672107";

    //代付接口
//	private static String url = "https://mobl-test.chinaums.com/channel/Business/UnifyMulti/202009";
    private static String url = "https://cloudpay.chinaums.com/channel/Business/UnifyMulti/202009";

    @Override
    public IPage<TmsCost> dispatchPage(String userName, TmsCost tmsCost, Long limit, Long pages) {
        IPage<TmsCost> page = new Page(pages, limit);
        List<TmsCost> tmsCosts = tmsCostMapper.dispatchPage(page, tmsCost);
        for(TmsCost cost : tmsCosts){
            String loadNo = cost.getLoadNo();
            if(StringUtils.isNotEmpty(loadNo)){
                String[] lns = loadNo.split(",");
                cost.setOrders(tmsCostMapper.costOrders(lns));
            }
        }
        page.setRecords(tmsCosts);
        return page;
    }

    @Override
    public IPage<TmsCost> auditPage(String userName, TmsCost tmsCost, Long limit, Long pages) {
        IPage<TmsCost> page = new Page(pages, limit);
        List<TmsCost> tmsCosts = tmsCostMapper.auditPage(page, tmsCost);
        for(TmsCost cost : tmsCosts){
            String loadNo = cost.getLoadNo();
            if(StringUtils.isNotEmpty(loadNo)){
                String[] lns = loadNo.split(",");
                cost.setOrders(tmsCostMapper.costOrders(lns));
            }
        }
        page.setRecords(tmsCosts);
        return page;
    }

    @Override
    public IPage<TmsCost> costReportPage(String userName, TmsCost tmsCost, Long limit, Long pages) {
        IPage<TmsCost> page = new Page(pages, limit);
        List<TmsCost> tmsCosts = tmsCostMapper.costReportPage(page, tmsCost);
        for(TmsCost cost : tmsCosts){
            String loadNo = cost.getLoadNo();
            if(StringUtils.isNotEmpty(loadNo)){
                String[] lns = loadNo.split(",");
                cost.setOrders(tmsCostMapper.costOrders(lns));
            }
        }
        page.setRecords(tmsCosts);
        return page;
    }

    @Override
    public BigDecimal sumFee(TmsCost tmsCost) {
        return tmsCostMapper.sumFee(tmsCost);
    }

    @Override
    public void costAdd(String userName, TmsCost tmsCost) {
        tmsCost.setIsValid(1);
        tmsCost.setCreateUser(userName);
        tmsCost.setCreateTime(LocalDateTime.now());
        tmsCost.setFeeType("out");
        tmsCostMapper.insert(tmsCost);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void costDel(String userName, TmsCost tmsCost) throws PredictableException{
        TmsCost tmsCostDb = tmsCostMapper.selectById(tmsCost.getId());
        if(!CostEnum.ENTRY.getValue().equals(tmsCostDb.getStatus())){
            throw new PredictableException("费用状态异常！");
        }
        LocalDateTime now = LocalDateTime.now();
        String[] loadNos = tmsCost.getLoadNo().split(",");
        QueryWrapper<TmsOrder> wrapper = new QueryWrapper<>();
        wrapper.in("load_no", loadNos);
        wrapper.eq("is_valid", 1);
        TmsOrder tmsOrder = new TmsOrder();
        tmsOrder.setUpdateUser(userName);
        tmsOrder.setUpdateTime(now);
        tmsOrder.setStatus(OrderEnum.SPLITED.getValue());
        tmsOrder.setPickFee(BigDecimal.valueOf(0));
        tmsOrder.setArteryFee(BigDecimal.valueOf(0));
        tmsOrder.setDropoffFee(BigDecimal.valueOf(0));
        tmsOrder.setWorkoverFee(BigDecimal.valueOf(0));
        tmsOrder.setLoadupFee(BigDecimal.valueOf(0));
        tmsOrder.setLoadoffFee(BigDecimal.valueOf(0));
        tmsOrder.setCarFee(BigDecimal.valueOf(0));
        tmsOrder.setFuelFee(BigDecimal.valueOf(0));
        tmsOrder.setCallbackFee(BigDecimal.valueOf(0));
        tmsOrder.setEscortinFee(BigDecimal.valueOf(0));
        tmsOrder.setTipFee(BigDecimal.valueOf(0));
        tmsOrder.setShuttleFee(BigDecimal.valueOf(0));
        tmsOrderMapper.update(tmsOrder, wrapper);
        tmsCostDb.setUpdateTime(now);
        tmsCostDb.setUpdateUser(userName);
        tmsCostDb.setIsValid(0);
        tmsCostDb.setStatus(CostEnum.CANCEL.getValue());
        tmsCostMapper.updateById(tmsCostDb);

        QueryWrapper<TmsCostOrder> dWapper = new QueryWrapper<>();
        dWapper.eq("cost_id", tmsCost.getId());
        tmsCostOrderMapper.delete(dWapper);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void costUpdate(String userName, TmsCost tmsCost) throws PredictableException {
        TmsCost tmsCostDb = tmsCostMapper.selectById(tmsCost.getId());
        /*if(CostEnum.PAY.getValue().equals(tmsCostDb.getStatus()) || CostEnum.PAY_FINISH.getValue().equals(tmsCostDb.getStatus())){
            throw new PredictableException("费用状态异常！");
        }*/
        if(!CostEnum.ENTRY.getValue().equals(tmsCostDb.getStatus())){
            throw new PredictableException("费用状态异常！");
        }
        LocalDateTime now = LocalDateTime.now();
        String[] split = tmsCost.getLoadNo().split(",");
        List<TmsOrder> tmsOrders = tmsCostMapper.costOrders(split);
        CostOrders costOrders = new CostOrders();
        costOrders.setOrders(tmsOrders);
        costOrders.setTmsCost(tmsCost);
        this.computeFee(costOrders);
        tmsCost.setUpdateUser(tmsCost.getUpdateUser());
        tmsCost.setUpdateTime(now);
        tmsCost.setStatus(CostEnum.ENTRY.getValue());
        tmsCostMapper.updateById(tmsCost);
        for(TmsOrder order : costOrders.getOrders()){
            TmsOrder tmsOrder = tmsOrderMapper.selectById(order.getId());
            if( !(tmsOrder.getStatus().equals(OrderEnum.DISPATCH.getValue()) ||
                tmsOrder.getStatus().equals(OrderEnum.COST_CONFIRMATION.getValue()) ||
                tmsOrder.getStatus().equals(OrderEnum.COST_AUDIT.getValue()) ||
                tmsOrder.getStatus().equals(OrderEnum.ORDER_AUDIT.getValue()) ||
                tmsOrder.getStatus().equals(OrderEnum.LOAD_IN.getValue()) ||
                tmsOrder.getStatus().equals(OrderEnum.LOAD_OFF.getValue()))){
                throw new PredictableException("订单状态异常！");
            }
            order.setStatus(OrderEnum.DISPATCH.getValue());
            order.setUpdateTime(now);
            order.setUpdateUser(userName);
            tmsOrderMapper.updateById(order);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void costOrders(String userName, CostOrders costOrders) throws PredictableException {
        computeFee(costOrders);
        LocalDateTime now = LocalDateTime.now();
        String orderIds = "";
        String loadNos = "";
        List<TmsOrder> orders = costOrders.getOrders();
        List<TmsOrder> collect = orders.stream().sorted((o1, o5) -> {
            return o1.getId().compareTo(o5.getId());
        }).collect(Collectors.toList());

        for(TmsOrder order : collect){
            orderIds += order.getId() + ",";
            loadNos += order.getLoadNo() + ",";
        }
        int i = tmsOrderMapper.checkCostOrderState(loadNos.split(","));
        if(i>0){
            throw new PredictableException("订单状态异常！");
        }

        for(TmsOrder order : collect){
            order.setStatus(OrderEnum.DISPATCH.getValue());
            order.setUpdateTime(now);
            order.setUpdateUser(userName);
            QueryWrapper<TmsCostOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", order.getId());
            List<TmsCostOrder> tmsCostOrders = tmsCostOrderMapper.selectList(queryWrapper);
            if(tmsCostOrders.size()>0){
                throw new PredictableException("有订单已经申请过费用！");
            }
            tmsOrderMapper.updateById(order);
        }

        TmsCost tmsCost = costOrders.getTmsCost();
        tmsCost.setCreateTime(now);
        tmsCost.setCreateUser(userName);
        tmsCost.setLoadNo(loadNos);
        tmsCost.setOrderIds(orderIds);
        tmsCost.setStatus(CostEnum.ENTRY.getValue());
        tmsCost.setIsValid(1);
        tmsCost.setFeeType("out");
        tmsCostMapper.insert(tmsCost);

        for(TmsOrder order : collect){
            TmsCostOrder tmsCostOrder = new TmsCostOrder();
            tmsCostOrder.setCostId(tmsCost.getId());
            tmsCostOrder.setOrderId(order.getId());
            tmsCostOrderMapper.insert(tmsCostOrder);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCost(String userName, TmsCost tmsCost) {
        LocalDateTime now = LocalDateTime.now();
        tmsCost.setUpdateUser(userName);
        tmsCost.setUpdateTime(now);
        tmsCost.setStatus(CostEnum.APPLY.getValue());
        tmsCostMapper.updateById(tmsCost);
        String[] loadNos = tmsCost.getLoadNo().split(",");
        QueryWrapper<TmsOrder> wrapper = new QueryWrapper<>();
        wrapper.in("load_no", loadNos);
        wrapper.orderByAsc("id");
        TmsOrder order = new TmsOrder();
        order.setUpdateTime(now);
        order.setUpdateUser(userName);
        order.setStatus(OrderEnum.COST_CONFIRMATION.getValue());
        tmsOrderMapper.update(order,wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditCost(String userName, List<TmsCost> tmsCosts) throws PredictableException{
        for(TmsCost tmsCost : tmsCosts){
            TmsCost tmsCostDb = tmsCostMapper.selectById(tmsCost.getId());
            LocalDateTime now = LocalDateTime.now();
            // 通过
            if(CostEnum.PASS.getValue().equals(tmsCost.getStatus())){
                if(!CostEnum.APPLY.getValue().equals(tmsCostDb.getStatus())){
                    throw new PredictableException(tmsCost.getLoadNo() + ": 状态异常！");
                }
                tmsCostDb.setUpdateTime(now);
                tmsCostDb.setUpdateUser(userName);
                tmsCostDb.setStatus(CostEnum.PASS.getValue());
                tmsCostMapper.updateById(tmsCostDb);
                String[] loadNos = tmsCost.getLoadNo().split(",");
                tmsOrderMapper.updateStatus(OrderEnum.COST_AUDIT.getValue(), loadNos);
            }
            // 驳回
            if(CostEnum.ENTRY.getValue().equals(tmsCost.getStatus())){
                if(!CostEnum.APPLY.getValue().equals(tmsCostDb.getStatus())){
                    throw new PredictableException(tmsCost.getLoadNo() + ": 状态异常！");
                }
                tmsCostDb.setUpdateTime(now);
                tmsCostDb.setUpdateUser(userName);
                tmsCostDb.setStatus(CostEnum.ENTRY.getValue());
                tmsCostMapper.updateById(tmsCostDb);
            /* String[] loadNos = tmsCost.getLoadNo().split(",");
            tmsOrderMapper.updateStatus(OrderEnum.SPLITED.getValue(), loadNos);*/
            }
            // 申请支付通过
            if(CostEnum.PAY.getValue().equals(tmsCost.getStatus())){
                if(!CostEnum.APPLY_PAY.getValue().equals(tmsCostDb.getStatus()) &&
                        !CostEnum.URGENT_PAY.getValue().equals(tmsCostDb.getStatus())){
                    throw new PredictableException(tmsCost.getLoadNo() + ": 状态异常！");
                }
                tmsCostDb.setUpdateTime(now);
                tmsCostDb.setUpdateUser(userName);
                tmsCostDb.setStatus(CostEnum.PAY.getValue());
                tmsCostMapper.updateById(tmsCostDb);
            }
            // 申请支付驳回
            if(CostEnum.REJECT_PAY.getValue().equals(tmsCost.getStatus())){
                if(!CostEnum.APPLY_PAY.getValue().equals(tmsCostDb.getStatus()) &&
                        !CostEnum.URGENT_PAY.getValue().equals(tmsCostDb.getStatus())){
                    throw new PredictableException(tmsCost.getLoadNo() + ": 状态异常！");
                }
                tmsCostDb.setUpdateTime(now);
                tmsCostDb.setUpdateUser(userName);
                if(CostEnum.APPLY_PAY.getValue().equals(tmsCostDb.getStatus())){
                    tmsCostDb.setStatus(CostEnum.PASS.getValue());
                }
                if(CostEnum.URGENT_PAY.getValue().equals(tmsCostDb.getStatus())){
                    tmsCostDb.setStatus(CostEnum.ENTRY.getValue());
                }

                tmsCostMapper.updateById(tmsCostDb);
            }

            // 支付成功
            if(CostEnum.PAY_FINISH.getValue().equals(tmsCost.getStatus())){
                if(!CostEnum.PAY.getValue().equals(tmsCostDb.getStatus())){
                    throw new PredictableException(tmsCost.getLoadNo() + ": 状态异常！");
                }
                tmsCostDb.setUpdateTime(now);
                tmsCostDb.setUpdateUser(userName);
                tmsCostDb.setPayNo(tmsCost.getPayNo());
                tmsCostDb.setStatus(CostEnum.PAY_FINISH.getValue());
                tmsCostMapper.updateById(tmsCostDb);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyPay(String userName, List<TmsCost> tmsCosts) throws PredictableException {
        LocalDateTime now = LocalDateTime.now();
        for(TmsCost tmsCost : tmsCosts){
            TmsCost dbCost = tmsCostMapper.selectById(tmsCost.getId());
            if(!CostEnum.PASS.getValue().equals(dbCost.getStatus())){
                throw new PredictableException("费用状态异常！");
            }
            /* int i = tmsOrderMapper.checkApplyPay(tmsCost.getLoadNo().split(","));
                if(i>0){
                throw new PredictableException("订单状态异常！");
            }*/

            dbCost.setStatus(CostEnum.APPLY_PAY.getValue());
            dbCost.setUpdateTime(now);
            if(tmsCost.getApplyPayTime() == null ){
                dbCost.setApplyPayTime(now);
            }else{
                dbCost.setApplyPayTime(tmsCost.getApplyPayTime());
            }
            dbCost.setUpdateUser(userName);
            tmsCostMapper.updateById(dbCost);
        }

    }

    @Override
    public void urgentCost(String userName, TmsCost tmsCost) throws PredictableException {

        LocalDateTime now = LocalDateTime.now();
        String[] split = tmsCost.getLoadNo().split(",");
        List<TmsOrder> tmsOrders = tmsCostMapper.costOrders(split);
        CostOrders costOrders = new CostOrders();
        costOrders.setOrders(tmsOrders);
        costOrders.setTmsCost(tmsCost);
        this.computeFee(costOrders);
        tmsCost.setUpdateUser(tmsCost.getUpdateUser());
        tmsCost.setUpdateTime(now);
        tmsCost.setApplyPayTime(now);
        tmsCost.setStatus(CostEnum.URGENT_PAY.getValue());
        tmsCostMapper.updateById(tmsCost);
        for(TmsOrder order : costOrders.getOrders()){
            TmsOrder tmsOrder = tmsOrderMapper.selectById(order.getId());
            if( !(tmsOrder.getStatus().equals(OrderEnum.DISPATCH.getValue()) ||
                    tmsOrder.getStatus().equals(OrderEnum.COST_CONFIRMATION.getValue()) ||
                    tmsOrder.getStatus().equals(OrderEnum.COST_AUDIT.getValue()) ||
                    tmsOrder.getStatus().equals(OrderEnum.ORDER_AUDIT.getValue()) ||
                    tmsOrder.getStatus().equals(OrderEnum.LOAD_IN.getValue()) ||
                    tmsOrder.getStatus().equals(OrderEnum.LOAD_OFF.getValue()))){
                throw new PredictableException("状态异常！");
            }
            // order.setStatus(OrderEnum.DISPATCH.getValue());
            order.setUpdateTime(now);
            order.setUpdateUser(userName);
            tmsOrderMapper.updateById(order);
        }

    }

    @Override
    public void finishCost(String userName, CostFinish costFinish) throws PredictableException {
        synchronized (this){
            String status = null;
            LocalDateTime now = LocalDateTime.now();
            TmsCost tmsCost = new TmsCost();
            if(CostEnum.PAY_ALLOW.getValue().equals(costFinish.getStatus())){
                status = CostEnum.PAY_FINISH.getValue();
                tmsCost.setPayFinishTime(now);
            }else if (CostEnum.PAY.getValue().equals(costFinish.getStatus())){
                status = CostEnum.PAY_ALLOW.getValue();
                tmsCost.setPayAllowTime(now);
                QueryWrapper<TmsCost> wrapper = new QueryWrapper<>();
                wrapper.in("id", costFinish.getIds());
                tmsCost.setStatus(status);
                tmsCost.setUpdateTime(now);
                tmsCost.setUpdateUser(userName);
                tmsCostMapper.update(tmsCost,wrapper);
                return;
            }else{
                throw new PredictableException("状态异常！");
            }
            int i = tmsCostMapper.checkFinish(costFinish.getIds(),costFinish.getStatus());
            if(i>0){
                throw new PredictableException("状态异常！");
            }

       /* QueryWrapper<TmsCost> wrapper = new QueryWrapper<>();
        wrapper.in("id", costFinish.getIds());

        tmsCost.setStatus(status);
        tmsCost.setUpdateTime(now);
        tmsCost.setUpdateUser(userName);
        tmsCost.setPayNo(costFinish.getPayNo());

        tmsCostMapper.update(tmsCost,wrapper);*/

            Boolean payCost = true;
            PayResponse payResponse = null;
            if(CostEnum.PAY_ALLOW.getValue().equals(costFinish.getStatus())){
                for(Long id : costFinish.getIds()){
                    QueryWrapper<TmsPayLog> plQw = new QueryWrapper<>();
                    plQw.eq("cost_id", id);
                    plQw.eq("status", 1);
                    plQw.eq("is_valid", 1);
                    Integer integer = tmsPayLogMapper.selectCount(plQw);
                    if(integer>0){
                        throw new PredictableException("重复支付！");
                    }
                    TmsCost tmsCost1 = tmsCostMapper.selectById(id);
                    BigDecimal sumFee = tmsCostMapper.sumFee(tmsCost1);
                    String orderId = UUID.fastUUID().toString().replace("-", "");
                    PayRequest payRequest = new PayRequest();
                    payRequest.setType(9);
                    payRequest.setOrderId(orderId);
                    payRequest.setPayAmt(sumFee.doubleValue());
                    payRequest.setAcctName(tmsCost1.getAccountName().trim().replace(" ",""));
                    payRequest.setAcctNo(tmsCost1.getBankAccount().trim().replace(" ",""));
                    payRequest.setBankName(BankUtil.getNameOfBank(tmsCost1.getBankAccount()));
                    payRequest.setPs("运费支付");
                    payRequest.setResume("运费支付");
                    payRequest.setPayerName("苏州鑫连鑫供应链管理有限公司");
                    payRequest.setPayerAcctNo("523568683202");
                    payResponse = payCost(payRequest);
                    if("99999999".equals(payResponse.getRespCode())){
                        payCost = true;
                    }else{
                        payCost = false;
                    }
                    TmsPayLog tmsPayLog = new TmsPayLog();
                    tmsPayLog.setCostId(id);
                    tmsPayLog.setCreateTime(now);
                    tmsPayLog.setCreateUser(userName);
                    tmsPayLog.setIsLock(0);
                    tmsPayLog.setIsValid(1);
                    tmsPayLog.setPayNo(orderId);
                    tmsPayLog.setStatus(payCost ? 1 : 0);
                    tmsPayLog.setRes(JSONUtil.toJsonPrettyStr(payResponse));
                    tmsPayLogMapper.insert(tmsPayLog);
                    if(payCost){
                        QueryWrapper<TmsCost> wrapper = new QueryWrapper<>();
                        wrapper.eq("id", id);
                        tmsCost.setStatus(status);
                        tmsCost.setUpdateTime(now);
                        tmsCost.setUpdateUser(userName);
                        tmsCost.setPayDate(LocalDate.now());
                        tmsCost.setPayNo(orderId);
                        tmsCostMapper.update(tmsCost,wrapper);
                    }else{
                        throw new PredictableException(payResponse == null ? "网银支付失败！" :payResponse.getRespMsg());
                    }
                }
            }
        }

    }

    @Override
    public void rejectCost(TmsCost tmsCost) throws PredictableException {
        String userName = RequestContextHolderUtil.getUserName();
        TmsCost tmsCost1 = tmsCostMapper.selectById(tmsCost.getId());
        if(!(CostEnum.PAY.getValue().equals(tmsCost1.getStatus()) || CostEnum.PAY_ALLOW.getValue().equals(tmsCost1.getStatus()))){
            throw new PredictableException("状态异常！");
        }

        tmsCost1.setStatus(CostEnum.APPLY_PAY.getValue());
        tmsCost1.setUpdateUser(userName);
        tmsCost1.setUpdateTime(LocalDateTime.now());
        tmsCostMapper.updateById(tmsCost1);
    }

    @Override
    public void updateAccount(TmsCost tmsCost) {
        TmsCost tmsCost1 = tmsCostMapper.selectById(tmsCost.getId());
        tmsCost1.setStatus(CostEnum.PAY_ALLOW.getValue());
        tmsCost1.setAccountName(tmsCost.getAccountName());
        tmsCost1.setBankAccount(tmsCost.getBankAccount());
        tmsCost1.setUpdateTime(LocalDateTime.now());
        tmsCost1.setUpdateUser(RequestContextHolderUtil.getUserName());
        tmsCostMapper.updateById(tmsCost1);
    }

    /**
     * 计算订单平均费用
     * @param costOrders
     */
    private void computeFee(CostOrders costOrders) throws PredictableException {
        TmsCost tmsCost = costOrders.getTmsCost();
        List<TmsOrder> orders = costOrders.getOrders();
        BigDecimal countVol = new BigDecimal("0");
        BigDecimal feeSum = new BigDecimal("0");
        Boolean isWt = false;
        for(TmsOrder order : orders) {
            if("V".equals(tmsCost.getAvgFlag())){
                BigDecimal volume = order.getVolume();
                if(volume == null){
                    throw new PredictableException("体积为空不能以体积为计费标准！");
                }
                countVol = countVol.add(volume);

            }
            if("W".equals(tmsCost.getAvgFlag())){
                BigDecimal weight = order.getWeight();
                if(weight == null){
                    throw new PredictableException("重量为空不能以重量为计费标准！");
                }
                countVol = countVol.add(weight);
            }

        }

        for(TmsOrder order : orders) {
            BigDecimal divideV = new BigDecimal("0");
            if("V".equals(tmsCost.getAvgFlag())){
                divideV = order.getVolume().divide(countVol, 20, BigDecimal.ROUND_HALF_UP);
            }
            if("W".equals(tmsCost.getAvgFlag())){
                divideV = order.getWeight().divide(countVol, 20, BigDecimal.ROUND_HALF_UP);
            }
            if("Z".equals(tmsCost.getAvgFlag())){
                divideV = new BigDecimal("1").divide(new BigDecimal(orders.size()), 20, BigDecimal.ROUND_HALF_UP);
            }
            if(tmsCost.getPickFee() != null){
                order.setPickFee(tmsCost.getPickFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getArteryFee() != null){
                order.setArteryFee(tmsCost.getArteryFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getDropoffFee() != null){
                order.setDropoffFee(tmsCost.getDropoffFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getWorkoverFee() != null){
                order.setWorkoverFee(tmsCost.getWorkoverFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getLoadupFee() != null){
                order.setLoadupFee(tmsCost.getLoadupFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getLoadoffFee() != null){
                order.setLoadoffFee(tmsCost.getLoadoffFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getCarFee() != null){
                order.setCarFee(tmsCost.getCarFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getFuelFee() != null){
                order.setFuelFee(tmsCost.getFuelFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getCallbackFee() != null){
                order.setCallbackFee(tmsCost.getCallbackFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getEscortinFee() != null){
                order.setEscortinFee(tmsCost.getEscortinFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getTipFee() != null){
                order.setTipFee(tmsCost.getTipFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if(tmsCost.getShuttleFee() != null){
                order.setShuttleFee(tmsCost.getShuttleFee().multiply(divideV).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
        }

        for(TmsOrder order : orders) {
            if(tmsCost.getPickFee() != null){
                feeSum = feeSum.add(order.getPickFee());
            }
            if(tmsCost.getArteryFee() != null){
                feeSum = feeSum.add(order.getArteryFee());
            }
            if(tmsCost.getDropoffFee() != null){
                feeSum = feeSum.add(order.getDropoffFee());
            }
            if(tmsCost.getWorkoverFee() != null){
                feeSum = feeSum.add(order.getWorkoverFee());
            }
            if(tmsCost.getLoadupFee() != null){
                feeSum = feeSum.add(order.getLoadupFee());
            }
            if(tmsCost.getLoadoffFee() != null){
                feeSum = feeSum.add(order.getLoadoffFee());
            }
            if(tmsCost.getCarFee() != null){
                feeSum = feeSum.add(order.getCarFee());
            }
            if(tmsCost.getFuelFee() != null){
                feeSum = feeSum.add(order.getFuelFee());
            }
            if(tmsCost.getCallbackFee() != null){
                feeSum = feeSum.add(order.getCallbackFee());
            }
            if(tmsCost.getEscortinFee() != null){
                feeSum = feeSum.add(order.getEscortinFee());
            }
            if(tmsCost.getTipFee() != null){
                feeSum = feeSum.add(order.getTipFee());
            }
            if(tmsCost.getShuttleFee() != null){
                feeSum = feeSum.add(order.getShuttleFee());
            }
        }

        BigDecimal subtract = feeSum.subtract(tmsCost.getPickFee())
                .subtract(tmsCost.getArteryFee())
                .subtract(tmsCost.getDropoffFee())
                .subtract(tmsCost.getWorkoverFee())
                .subtract(tmsCost.getLoadupFee())
                .subtract(tmsCost.getLoadoffFee())
                .subtract(tmsCost.getCarFee())
                .subtract(tmsCost.getFuelFee())
                .subtract(tmsCost.getCallbackFee())
                .subtract(tmsCost.getEscortinFee())
                .subtract(tmsCost.getTipFee())
                .subtract(tmsCost.getShuttleFee());

        TmsOrder order = orders.get(0);
        if(order.getPickFee() != null && order.getPickFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setPickFee(order.getPickFee().subtract(subtract));
            isWt = true;
        }
        if(order.getArteryFee() != null && order.getArteryFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setArteryFee(order.getArteryFee().subtract(subtract));
            isWt = true;
        }
        if(order.getDropoffFee() != null && order.getDropoffFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setDropoffFee(order.getDropoffFee().subtract(subtract));
            isWt = true;
        }
        if(order.getWorkoverFee() != null && order.getWorkoverFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setWorkoverFee(order.getWorkoverFee().subtract(subtract));
            isWt = true;
        }
        if(order.getLoadupFee() != null && order.getLoadupFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setLoadoffFee(order.getLoadoffFee().subtract(subtract));
            isWt = true;
        }
        if(order.getLoadoffFee() != null && order.getLoadoffFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setLoadoffFee(order.getLoadoffFee().subtract(subtract));
            isWt = true;
        }
        if(order.getCarFee() != null && order.getCarFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setCarFee(order.getCarFee().subtract(subtract));
            isWt = true;
        }
        if(order.getFuelFee() != null && order.getFuelFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setFuelFee(order.getFuelFee().subtract(subtract));
            isWt = true;
        }
        if(order.getCallbackFee() != null && order.getCallbackFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setCallbackFee(order.getCallbackFee().subtract(subtract));
            isWt = true;
        }
        if(order.getEscortinFee() != null && order.getEscortinFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setEscortinFee(order.getEscortinFee().subtract(subtract));
            isWt = true;
        }
        if(order.getTipFee() != null && order.getTipFee().compareTo(BigDecimal.ZERO) != 0 && !isWt){
            order.setTipFee(order.getTipFee().subtract(subtract));
            isWt = true;
        }
        if(order.getShuttleFee() != null && order.getShuttleFee().compareTo(BigDecimal.ZERO) !=0 && !isWt){
            order.setShuttleFee(order.getShuttleFee().subtract(subtract));
        }
    }


    private PayResponse payCost(PayRequest payRequest){
        Map<String, Object> body = new HashMap<>();
        //header
        body.put("transCode", TransCode.helpPay);  //交易码
        body.put("verNo", "100");		//版本号100-固定值
        body.put("srcReqDate", DateUtil.format(DateUtil.date(), "yyyyMMdd"));	//请求系统日期  格式：YYYYMMDD
        body.put("srcReqTime", DateUtil.format(DateUtil.date(), "HHmmss"));	//请求系统时间  格式：hhmmss
        body.put("srcReqId", payRequest.getOrderId());	//请求系统流水号 每一笔报文请求的流水号，与系统日期一起唯一标识一笔请求，由商户自行生成
        body.put("channelId", "043");//渠道号 043-固定值
        body.put("groupId", "XLXGYL");//集团号  集团接入商户资金自主管理系统的集团号，接入时我司会为商户分配集团号
        body.put("signature", "");//签名

        //商户信息
        body.put("merNo", merNo);//企业用户号100010000*****
        body.put("acctType", "3");//3-转款账户
        body.put("payAmt", Convert.toStr(MoneyUtil.Yuan2Fen(payRequest.getPayAmt())));//代付金额	单位分
        body.put("acctName", payRequest.getAcctName());	//收款账户名称
        body.put("acctNo", DBTripleDesUtil.encrypt(payRequest.getAcctNo()));//收款账户号
        body.put("bankNo", "000000000000");//开户行行号
        body.put("bankName", payRequest.getBankName());//开户行名称
        body.put("matchMode", "1");//行名行号匹配模式 1-固定值
        body.put("ps", payRequest.getPs());//附言
        body.put("resume", payRequest.getResume());//摘要 长度最大为20个字节（汉字长度为2）
        body.put("payerName", payRequest.getPayerName());//付款方名称 收款银行回单显示用
        body.put("payerAcctNo", DBTripleDesUtil.encrypt(payRequest.getPayerAcctNo()));//付款方账号
        body.put("reserve1", "");//预留
        body.put("reserve2", "");//预留
        String sign = SignUtil.sign(body);
        body.put("signature", sign);//签名
        String post = HttpUtil.post(url, JSONUtil.toJsonStr(body));
        PayResponse payResponse = JSONUtil.toBean(post, PayResponse.class);
        return payResponse;
    }

}
